﻿Create Trigger T1_CTPhieuNhap 
on CTPhieuNhap for insert
as Begin
	Update PhieuNhap
	Set TongTien=TongTien + Inserted.ThanhTien,TongSL=TongSL+ Inserted.SoLuong
	from Inserted
	where PhieuNhap.MaPN=Inserted.MaPN
end
go
Create Trigger T2_CTPhieuNhap
on CTPhieuNhap for Delete
as Begin
	Declare @Mapn nvarchar(10),@Masp nvarchar (8),@ThanhTien numeric,@TongSL int
	Select @Mapn=Mapn,@Masp=Masp,@TongSL=SoLuong,@ThanhTien=ThanhTien from Deleted
	Update PhieuNhap
	Set TongTien=TongTien - @ThanhTien,TongSL=TongSL - @TongSL
	where Mapn=@Mapn
end
go
Create Trigger T3_CTPhieuNhap
on CTPhieuNhap for Update
as Begin
	Declare @Mapn nvarchar(10),@Masp nvarchar (8),@ThanhTien numeric,@TongSL int,@ThanhTienNew numeric,@TongSLNew int
	Select @Mapn=Mapn,@Masp=Masp,@TongSL=SoLuong,@ThanhTien=ThanhTien from Updated
	IF @Tongsl>@TongSLNew and @ThanhTien>@ThanhTienNew
	Update PhieuNhap
		Set TongTien=TongTien - (@ThanhTien-@ThanhTienNew),TongSL=TongSL - (@TongSL-@TongSLNew)
	where Mapn=@Mapn
end
go
------------------------ Hóa Đơn----------------
Create Trigger T1_CTHoaDon
on CTHoaDon for insert
as Begin
	Update HoaDon
	Set TongTien=TongTien + Inserted.ThanhTien,TongSL=TongSL+ Inserted.SoLuong
	from Inserted
	where HoaDon.MaHD=Inserted.MaHD
end
go
Create Trigger T2_CTHoaDon
on CTHoaDon for Delete
as Begin
	Declare @Mahd nvarchar(10),@Masp nvarchar (8),@ThanhTien numeric,@TongSL int
	Select @Mahd=Mahd,@Masp=Masp,@TongSL=SoLuong,@ThanhTien=ThanhTien from Deleted
	Update HoaDon
	Set TongTien=TongTien - @ThanhTien,TongSL=TongSL - @TongSL
	where Mahd=@Mahd
end
----------------
create trigger T1_SL_CTHD -- ok
on CTHoaDon
for insert,update as
if exists (select * from inserted 
               where inserted.SoLuong<=0)
	begin
	       raiserror('Số lượng nhập phải lớn hơn 0 ',16,1)
	       rollback tran
	end
go
------------------------san pham

Create Trigger T2_SanPham_Ton
on CTPhieuNhap for insert
as Begin
	Update TonSP
	Set TongSP=TongSP + Inserted.SoLuong
	from Inserted
	where TonSP.Masp=Inserted.Masp
end
go

Create Trigger HoaDon_Ton
on CTHoaDOn for insert
as Begin

	Update TonSP
	Set TongSP=TongSP - Inserted.SoLuong
	from Inserted
	where TonSP.Masp=Inserted.Masp
end
go

create trigger ThongBao_HoaDon_Ton
on CTHoaDon
for insert,update as
if exists (select soluongsp from inserted 
               where inserted.Tonsp<=0)
	begin
	       raiserror('Số lượng nhập phải lớn hơn 0 ',16,1)
	       rollback tran
	end
go
---